package com.hoshiicloud.user.service.impl.rbac;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.rbac.entity.SysOrganization;
import com.hoshiicloud.rbac.entity.SysPlatform;
import com.hoshiicloud.user.feign.INeo4jService;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.rbac.SysOrganizationMapper;
import com.hoshiicloud.user.mapper.rbac.SysPermissionesMapper;
import com.hoshiicloud.user.mapper.rbac.SysPlatformMapper;
import com.hoshiicloud.user.param.rbac.RObject;
import com.hoshiicloud.user.service.rbac.ISysOrganizationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 系统组织 服务实现类
 * </p>
 *
 * @author Mr.Wu
 * @since 2019-04-18
 */
@Service
public class SysOrganizationServiceImpl extends ServiceImpl<SysOrganizationMapper, SysOrganization>
		implements ISysOrganizationService {


	private INeo4jService neo4JService;


	private IdGeneratorService idGeneratorRemote;

	@Autowired
	private SysPermissionesMapper sysPermissionesMapper;

	@Autowired
	private SysOrganizationMapper sysOrganizationMapper;

	@Autowired
	private SysPlatformMapper sysPlatformMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response addDept(SysOrganization param) {
		// 获取全局id
		String id = idGeneratorRemote.queryGeneratorId();
		if (StringUtils.isBlank(id)) {
			throw new ServiceException(CommonError.error("id服务失败"));
		}
		// 调用内置工具产生ID
		param.setId(Long.valueOf(id));
		param.setCreatedTime(LocalDateTime.now());
		sysOrganizationMapper.insert(param);
		Response result = null;
		String label="";
		if (param.getPId() != null) {
			// 插入上级部门节点
			// 搜索上级部门名称
			SysOrganization parentDept = sysOrganizationMapper.selectById(param.getPId());
			if (parentDept == null) {
				throw new ServiceException(CommonError.error("搜索上级平台失败"));
			}
			label=parentDept.getName();
		} else if (param.getPlatformId() != null) {
			// 插入平台节点

			// 搜索上级平台名称
			SysPlatform platform = sysPlatformMapper.selectById(param.getPlatformId());
			if (platform == null) {
				throw new ServiceException(CommonError.error("搜索上级平台失败"));
			}
			label=platform.getName();

		}
		// 插入neo4j节点
		RObject neo4jParam = new RObject();
		// 部门所属平台名称
		neo4jParam.setLabel(label);
		neo4jParam.setUuid(id);
		neo4jParam.addProperty("uuid", id);
		neo4jParam.addProperty("name", param.getName());
		result = neo4JService.addRole(neo4jParam);
		if (result != null && !result.isSuccess()) {
			throw new ServiceException(CommonError.error("neo4j服务失败," + result.getMsg()));
		} else if (result == null) {
			throw new ServiceException(CommonError.error("neo4j服务失败"));
		}
		return Response.success("新增成功");
	}

	@Override
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response deleteDept(String id) {
		int count = sysOrganizationMapper.deleteById(id);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("删除失败"));
		} else {
			return Response.success("删除成功");
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
	public Response<SysOrganization> getDetail(String id) {
		SysOrganization sysOrganization = sysOrganizationMapper.selectById(id);
		if (sysOrganization == null) {
			return Response.failed("数据不存在");
		} else {
			return Response.data(sysOrganization);
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5('Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	public Response<List<SysOrganization>> getList(Wrapper<SysOrganization> queryWrapper) {
		return Response.data(sysOrganizationMapper.selectList(queryWrapper));
	}

	@Override
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response updateDept(SysOrganization param) {
		int count = sysOrganizationMapper.updateById(param);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("修改失败"));
		} else {
			return Response.success("修改成功");
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
	public IPage<SysOrganization> getPage(IPage<SysOrganization> page, QueryWrapper<SysOrganization> queryWrapper, String key) {
		return sysOrganizationMapper.selectPage(page, queryWrapper);
	}

}
